<?php
namespace Foam\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;

class FicheTechniqueTable extends AbstractTableGateway
{
    protected $table ='foam_fiche_technique';
    
    public function __construct(Adapter $adapter)
    {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new FicheTechnique());
        $this->initialize();
    }
    
    public function fetchAll()
    {
        $resultSet = $this->select();
        return $resultSet;
    }
    
    public function getFicheTechnique($id_produit)
    {
        $id_produit  = (int) $id_produit;
        $adapter = $this->adapter;
        $sql = new Sql($adapter);
        $select = $sql->select();
        $select->from(array('ftk' => $this->table));
        $select->join(array('ing' => 'foam_ingredient'), 
                        'ftk.id_ingredient = ing.id_ingredient',
                        array('inglibelle' => 'libelle'));
        $select->join(array('frs' => 'foam_fournisseur'), 
                        'ing.id_fournisseur = frs.id_fournisseur',
                        array('frslibelle' => 'libelle'));
        $select->join(array('dlc' => 'foam_dlc'), 
                        'ing.id_dlc = dlc.id_dlc',
                        array('dlclibelle' => 'libelle'));
        
        $where = new Where();
        $where->equalTo('id_produit', $id_produit);
        $select->where($where);
        
        $selectString = $sql->getSqlStringForSqlObject($select);
        $results = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);   
        return $results;
    }
    
    public function saveFiche($id_fiche,$id_ingredient,$quantite,$condition,$conservation,$cadencier,$id_produit)
    {
        if($id_fiche == ""){
            $data = array(
                'id_fiche' => $id_fiche,
                'id_ingredient' => $id_ingredient,
                'quantite' => $quantite,
                'condition' => $condition,
                'conservation' => $conservation,
                'cadencier' => $cadencier,
                'id_produit' => $id_produit,
            );
            
            $this->insert($data);
        }
    }
    
    public function updateFicheProduitId($id_produit)
    {
        $data = array(
            'id_produit' => $id_produit,
        );
        
        $this->update($data, array('id_produit' => 0));
    }
    
    public function deleteByProduit($id)
    {
        $this->delete(array('id_produit' => $id));
    }
    
    public function deleteByCancel()
    {
        $this->delete(array('id_produit' => 0));
    }
}
